<template>
  <div class="cart">
    <Header title="购物车">
      <span slot="left"></span>
    </Header>
    <template v-if="carts.length>0">
      <div class="content">
        <div class="all-choose">
          <yd-checkbox color="#369eee" shape="circle" v-model="isCheckAll">全选</yd-checkbox>
        </div>

        <div class="cart-list">
          <VueSlideOptions v-for="(item,index) in carts" :key="index">
            <div class="cart-list-item" slot="cover">
              <yd-flexbox>
                <yd-checkbox color="#369eee" v-model="item.checked" shape="circle"></yd-checkbox>
                <div class="pic" :style="{background: `url(${item.pic}) no-repeat center center / contain`}"></div>
                <yd-flexbox-item align="top">
                  <h2>{{item.name}}</h2>
                  <p>￥{{item.price | price}}</p>
                  <yd-spinner class="spinner" max="1000" min="1" unit="1" v-model="item.quantity"></yd-spinner>
                </yd-flexbox-item>
              </yd-flexbox>
            </div>
            <div @click="del(item.id)" slot="options" class="del">
              删除
            </div>
          </VueSlideOptions>
        </div>

      </div>
      <div class="bottom">
        <span class="choose">已选:{{selectCount}}</span>
        <span class="amount">合计：
          <i>￥{{amount | price}}</i>
        </span>
        <router-link to="/settle">结算</router-link>
      </div>
    </template>
    <template v-else>
      <div class="carts-not-product">
        购物车暂时没有商品
        <yd-button @click.native="goHome">继续购物</yd-button>
      </div>
    </template>
    <Tabbar></Tabbar>
  </div>
</template>
<script>
import VueSlideOptions from "vue-slide-options";
import { mapState } from "vuex";
/* 

  对购物车的任何操作，都要发送请求
*/
export default {
  name: "Cart",
  components: {
    VueSlideOptions
  },
  computed: {
    ...mapState({
      carts: state => state.carts
    }),
    amount() {
      return this.carts.filter(item => item.checked).reduce((cur, item) => {
        return cur + item.quantity * item.price;
      }, 0);
    },
    isCheckAll: {
      get() {
        return this.carts.every(item => item.checked);
      },
      set(val) {
        // console.log(arguments,'set');
        this.carts.forEach(item => {
          item.checked = val;
        });
      }
    },
    selectCount() {
      return this.carts.filter(item => item.checked).length;
    }
  },
  data() {
    return {
      arr: []
    };
  },
  created() {
    console.log(this.carts);
  },
  methods: {
    del(id) {
      const index = this.carts.findIndex(item => item.id === id);
      const c = this.carts[index];
      this.$dialog.confirm({
        title: "提示",
        mes: "确定要删除？",
        opts: () => {
          this.carts.splice(index, 1);
          this.$dialog.toast({ mes: "删除成功", timeout: 1000 });
        }
      });
    },
    goHome(){
      console.log(123213)
      this.$router.push('/home')
    }
  }
};
</script>

